package com.grow.greenhouse.utils;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.zhipu.oapi.ClientV4;
import com.zhipu.oapi.Constants;
import com.zhipu.oapi.service.v4.model.*;
import org.apache.commons.lang3.StringUtils;

import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

import static com.zhipu.oapi.demo.V4OkHttpClientTest.defaultObjectMapper;
import static com.zhipu.oapi.demo.V4OkHttpClientTest.mapStreamToAccumulator;

public  class ZhiPuUtil {

    private static Gson gson = new Gson();

    public static String API_KEY = "d5fecff7484357ebb347a72b24efa695";

    public static String API_SECRET = "7IIINgAomohMvAZk";

    public static String requestIdTemplate = "greenhouse-%d";

    public static final ClientV4 client = new ClientV4.Builder(API_KEY,API_SECRET).build();

    public static final ObjectMapper mapper = defaultObjectMapper();

    public static String Invoke(String question) {
        List<ChatMessage> messages = new ArrayList<>();
        ChatMessage chatMessage = new ChatMessage(ChatMessageRole.USER.value(), question);
        messages.add(chatMessage);
        String requestId = String.format(requestIdTemplate, System.currentTimeMillis());
        // 函数调用参数构建部分
        List<ChatTool> chatToolList = new ArrayList<>();
        ChatTool chatTool = new ChatTool();
        chatTool.setType(ChatToolType.RETRIEVAL.value());
        Retrieval retrieval = new Retrieval();
        retrieval.setKnowledge_id("1766700012596793344");
        retrieval.setPrompt_template("从文档{{knowledge}}中找问题{{question}}的答案，找到答案就仅使用文档语句回答问题， 回答中不要再加上{{question}}的内容，直接回答。");
        chatTool.setRetrieval(retrieval);
        chatToolList.add(chatTool);
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                .model(Constants.ModelChatGLM4)
                .stream(Boolean.FALSE)
                .invokeMethod(Constants.invokeMethod)
                .messages(messages)
                .requestId(requestId)
                .tools(chatToolList)
                .toolChoice("auto")
                .build();
        ModelApiResponse invokeModelApiResp = client.invokeModelApi(chatCompletionRequest);
        String content = "";
        try {
            content = mapper.writeValueAsString(invokeModelApiResp.getData()
                    .getChoices().get(0).getMessage().getContent());
            content = StringUtils.replace(content,"\\n\\n","");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return content;
    }

    private static ModelData getModelData(ChatMessageAccumulator chatMessageAccumulator, ChatCompletionRequest chatCompletionRequest) {
        Choice choice = new Choice(chatMessageAccumulator.getChoice().getFinishReason(), 0L, chatMessageAccumulator.getDelta());
        List<Choice> choices = new ArrayList<>();
        choices.add(choice);
        ModelData data = new ModelData();
        data.setChoices(choices);
        data.setUsage(chatMessageAccumulator.getUsage());
        data.setId(chatMessageAccumulator.getId());
        data.setCreated(chatMessageAccumulator.getCreated());
        data.setRequestId(chatCompletionRequest.getRequestId());
        return data;
    }
}
